package com.hb.trans.mvp.ui.activity


import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.appcompat.app.AlertDialog
import android.view.MenuItem
import android.widget.ImageView
import cn.bingoogolapple.bgabanner.BGABanner
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.basiclib.base.BaseActivity
import com.basiclib.utils.gotoPermissionSettings
import com.hb.trans.R
import com.hb.trans.bean.Banner
import com.hb.trans.bean.EnrollCount
import com.hb.trans.bean.School
import com.hb.trans.bean.SchoolDetail
import com.hb.trans.global.ACTIVITY_SCHOOL_INFO
import com.hb.trans.global.ACTIVITY_SIGN
import com.hb.trans.mvp.contract.SchoolInfoContract
import com.hb.trans.mvp.presenter.SchoolInfoPresenter
import com.hb.trans.mvp.ui.fragment.SchoolInfoItemFragment
import com.jakewharton.rxbinding2.view.clicks
import com.tbruyelle.rxpermissions2.RxPermissions
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_school_info_new.*
import javax.inject.Inject


/**
 * 驾校信息
 */

@Route(path = ACTIVITY_SCHOOL_INFO)
class SchoolInfoActivity : BaseActivity(), BGABanner.Adapter<ImageView, Banner>,
    BGABanner.Delegate<ImageView, Banner>, SchoolInfoContract.View {
    override fun setupEnrollCount(enrollCount: EnrollCount?) {
        this.enrollCount = enrollCount
        enrollCount?.let {
            schoolNewCount.text = it.count.toString() + "人"
        }
    }

    override fun setupSchoolDetail(detail: SchoolDetail?) {
        this.schoolDetail = detail
        schoolDetail?.let {
            schoolNewAddress.text = it.address
            schoolNewName.text = it.name
        }
    }

    @JvmField
    @Autowired
    var schoolInfo: School? = null
    var schoolDetail: SchoolDetail? = null
    var enrollCount: EnrollCount? = null

    @Inject
    lateinit var mPresenter: SchoolInfoPresenter

    override fun getPresenter(): SchoolInfoPresenter? = mPresenter

    override fun getContentViewResId(): Int = R.layout.activity_school_info_new

    override fun onActivityInject() {
        AndroidInjection.inject(this)
    }

    override fun attachView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        mPresenter.attachView(this)
    }


    override fun initView() {
        setSupportActionBar(schoolInfoToolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.setHomeAsUpIndicator(R.mipmap.ic_left_arrow)

        schoolInfoCollapsingToolbarLayout.title = "驾校信息"
        schoolInfoCollapsingToolbarLayout.setExpandedTitleColor(Color.WHITE)
        schoolInfoCollapsingToolbarLayout.setCollapsedTitleTextColor(Color.WHITE)

        initBanner()
        initTab()

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> onBackPressed()
        }
        return true
    }

    private fun initBanner() {
        banner.setAdapter(this)
        banner.setDelegate(this)
        banner.setData(null, null, R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner1, R.mipmap.banner2);
    }


    override fun onBannerItemClick(banner: BGABanner?, itemView: ImageView?, model: Banner?, position: Int) {}

    override fun fillBannerItem(banner: BGABanner?, itemView: ImageView?, model: Banner?, position: Int) {}

    private fun initTab() {
        var mTitle = listOf("班型", "训练场", "教练")

        var schoolInfo1Fragment = SchoolInfoItemFragment()
//        var bundle1 = Bundle()
//        bundle1.putString("inscode", schoolInfo?.inscode)
//        schoolInfo1Fragment.setArguments(bundle1)


        var schoolInfo2Fragment = SchoolInfoItemFragment()

        var schoolInfo3Fragment = SchoolInfoItemFragment()
        var bundle3 = Bundle()
        bundle3.putString("inscode", schoolInfo?.inscode)
        schoolInfo3Fragment.setArguments(bundle3)


        var mFragment = listOf(
            schoolInfo1Fragment, schoolInfo2Fragment,
            schoolInfo3Fragment
        )
        schoolInfoTabLayout.addTab(schoolInfoTabLayout.newTab().setText(mTitle[0]))
        schoolInfoTabLayout.addTab(schoolInfoTabLayout.newTab().setText(mTitle[1]))
        schoolInfoTabLayout.addTab(schoolInfoTabLayout.newTab().setText(mTitle[2]))
        schoolInfoTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                //选中Tab
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                //未选中Tab
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                //再次选中
            }
        })

        schoolInfoViewPager.adapter = object :
            androidx.fragment.app.FragmentPagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int): androidx.fragment.app.Fragment {
                return mFragment[position]
            }

            override fun getCount(): Int {
                return mFragment.size
            }

            override fun getPageTitle(position: Int): CharSequence? {
                return mTitle.get(position)
            }
        }
        schoolInfoTabLayout.setupWithViewPager(schoolInfoViewPager)
//        schoolInfoTabLayout.getTabAt(2)!!.select()

    }

    override fun initData() {
        mPresenter.getSchoolCoach(schoolInfo?.inscode)
//
    }

    override fun onResume() {
        super.onResume()
        mPresenter.getEnrollCount(schoolInfo?.inscode)
    }


    @SuppressLint("CheckResult")
    override fun setListener() {
//        schoolInfoToolbar.backClick()?.subscribe { finish() }
        schoolInfoSign.clicks().subscribe {
            ARouter.getInstance().build(ACTIVITY_SIGN)
                .withString("name", schoolDetail?.name)
                .withString("inscode", schoolDetail?.inscode)
                .withString("busiscope", schoolDetail?.busiscope)
                .navigation()
        }

        schoolNewCall.clicks().subscribe {
            val permissions = RxPermissions(this)
            permissions.request(Manifest.permission.CALL_PHONE)
                .subscribe {
                    if (it) {
                        schoolDetail?.let { schoolDetail ->
                            if (!schoolDetail.phone.isNullOrBlank()) {
                                AlertDialog.Builder(this)
                                    .setTitle("提示")
                                    .setMessage("立即联系${schoolInfo?.shortname}?")
                                    .setCancelable(true)
                                    .setPositiveButton("拨打") { dialog, _ ->
                                        dialog.dismiss()
                                        val intent = Intent()
                                        intent.action = Intent.ACTION_CALL
                                        intent.data = Uri.parse("tel:${schoolDetail.phone}")
                                        startActivity(intent)
                                    }
                                    .setNegativeButton("取消") { dialog, _ -> dialog?.dismiss() }
                                    .show()
                            } else {
                                showShortToast("暂未有驾校联系电话")
                            }
                        }
                    } else {
                        AlertDialog.Builder(this)
                            .setTitle("提示")
                            .setMessage("电话权限没有打开，请到打开权限后再尝试！")
                            .setCancelable(true)
                            .setPositiveButton("设置") { dialog, _ ->
                                dialog.dismiss()
                                gotoPermissionSettings(false)
                            }
                            .show()
                    }
                }
        }
    }
}
